# -*- coding: utf-8 -*-

"""
飞机大战游戏精灵类
@Author: 芮芪懿 QQ1849433491
@Project->File: pygame_train -> game_sprites.py
@IDE：PyCharm
@File: game_sprites.py
@Datetime: 2021/7/9 14:30
"""
import random
import pygame  # 导入pygame模块
from resource_path import *  # 导入图片资源路径
from pygame.sprite import Sprite, Group  # 引入精灵类
from game_public import *
from game_main import FRAME_RATE

SCREEN_RECT = create_rect(0, 0, 480, 800)  # 屏幕大小最好和背景大小一致
PLAYER_IMAGE_MARGIN_BOTTOM = 200  # 玩家飞机距底部距离


class BaseGameSprite(pygame.sprite.Sprite):
    """游戏精灵基类"""

    def __init__(self, imagePath: str = "", moveSpeed: int = 2):
        """
        初始化游戏精灵基类
        :param imagePath: 图片路径
        :param moveSpeed: 移动速度
        """
        super().__init__()
        self.image = load_image_resource(imagePath)
        self.rect = self.image.get_rect()
        self.imageWidth = self.rect.width
        self.imageHeight = self.rect.height
        self.moveSpeed = moveSpeed
        self.offImages = []
        for imagePath in PLANE_OFF_IMAGES_PATH:
            self.offImages.append(load_image_resource(imagePath))
        pass


class GameBackgroundSprite(Sprite):
    """
    游戏背景精灵类
    """

    def __init__(self, bgImagePath: str = bgImagePath, moveSpeed: int = 3, isTopBgimage: bool = False):
        """
        背景精灵类构造函数
        :param bgImagePath: 图片路径
        :param moveSpeed: 移动速度
        :param isTopBgimage: 是否是底部的图片
        """
        super().__init__()
        self.image = load_image_resource(bgImagePath)
        self.rect = self.image.get_rect()
        # 判断是否是底部的图片，设置y值为自身的高度
        if isTopBgimage:
            self.rect.y = - self.rect.height
        self.moveSpeed = moveSpeed

    def update(self):
        """
        重写在屏幕移动的位置 -> 在屏幕垂直方向向下移动
        :return:
        """
        self.rect.y += self.moveSpeed
        # 判断是否移出屏幕外重置y值
        if self.rect.y >= self.rect.height:
            self.rect.y = -self.rect.height


class PlayerPlaneSprite(BaseGameSprite):
    """
    @Author: 芮芪懿
    @Datetime: 2021/7/9 15:07
    玩家飞机精灵类
    """

    def __init__(self, imagePath=PLAYER1_IMAGE_PATH):
        super().__init__(imagePath, moveSpeed=2)
        # super().__init__()
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.y = SCREEN_RECT.height - PLAYER_IMAGE_MARGIN_BOTTOM
        self.moveDirection = " "
        self.flag = True
        self.isDestroy = False
        player2Image = load_image_resource(PLAYER2_IMAGE_PATH)
        self.images = [self.image, player2Image]
        self.counter = 0  # 用于计数切换图片
        self.bulletGroup = Group()
        self.index = 0
        pass

    def update(self):
        """
        重写更新屏幕方法
        :param moveDirection: 移动方向: ad->左右移动,ws->上下移动
        :return:
        """

        # 玩家飞机火焰图片控制
        self.counter += 1
        if self.counter > (FRAME_RATE / 2):
            self.flag = False
        if self.counter == FRAME_RATE:
            self.flag = True
            self.counter = 0
        if self.flag:
            # print("tu1")
            self.image = self.images[0]
        else:
            # print("tu2")
            self.flag = not self.flag
            self.image = self.images[1]


        # 判断移动方向,ad是左右,ws是上下
        if self.moveDirection == "ad":
            self.rect.x += self.moveSpeed
        elif self.moveDirection == "ws":
            self.rect.y += self.moveSpeed
        else:
            self.rect.x += 0
            self.rect.y += 0

        # 控制玩家飞机不可移出屏幕外
        if self.rect.top <= SCREEN_RECT.top:
            self.rect.top = 0
        elif self.rect.right >= SCREEN_RECT.right:
            self.rect.right = SCREEN_RECT.right
        elif self.rect.bottom >= SCREEN_RECT.bottom:
            self.rect.bottom = SCREEN_RECT.bottom
        elif self.rect.left <= 0:
            # print("当前的飞机x位置: ", self.rect.x)
            self.rect.left = 0

        if self.isDestroy:
            self.plane_destroy()

    def fire(self):
        """玩家飞机开火"""
        for i in (0, 1):
            # 创建子弹精灵
            bullet = Bullet()
            # 设置精灵的位置
            bullet.rect.bottom = self.rect.y - (bullet.rect.height + 5) * i
            bullet.rect.centerx = self.rect.centerx

            # 将精灵添加到精灵组
            self.bulletGroup.add(bullet)

    def super_fire(self):
        """玩家飞机开挂火力"""

        # 创建子弹精灵
        bullet = Bullet()
        # 设置精灵的位置
        bullet.rect.bottom = self.rect.y - (bullet.rect.height + 5)
        bullet.rect.centerx = self.rect.centerx

        bullet2 = Bullet()
        # 设置精灵的位置
        bullet2.rect.bottom = self.rect.y + (bullet.rect.height + 10)
        bullet2.rect.x = self.rect.left + 15

        bullet3 = Bullet()
        # 设置精灵的位置
        bullet3.rect.bottom = self.rect.y + (bullet.rect.height + 10)
        bullet3.rect.x = self.rect.right - 20

        # 将精灵添加到精灵组
        self.bulletGroup.add(bullet, bullet2, bullet3)

    def plane_destroy(self):
        self.index += 1
        self.imageFrameZoneSize = FRAME_RATE / len(self.offImages)  # 图片帧空间大小
        if self.index < self.imageFrameZoneSize:
            self.image = self.offImages[0]
        elif self.imageFrameZoneSize < self.index < self.imageFrameZoneSize * 2:
            self.image = self.offImages[1]
        elif self.imageFrameZoneSize * 2 < self.index < self.imageFrameZoneSize * 3:
            self.image = self.offImages[2]
        elif self.index == self.imageFrameZoneSize * len(self.offImages):
            self.index = 0
        pass


class Bullet(BaseGameSprite):
    """子弹精灵"""

    def __init__(self):
        super().__init__(BULLET_IMAGE_PATH, -1)
        self.counter = 0  # 用于计数切换图片
        self.flag = True
        self.temImage = self.image

    def update(self):
        self.rect.y += self.moveSpeed
        if self.rect.bottom < 0:
            self.kill()

    def __del__(self):
        pass
        # print("子弹被销毁...")


class Enemy(BaseGameSprite):
    """敌机精灵"""

    def __init__(self,moveSpeed:int = 3):
        super().__init__(ENEMY_IMAGE_PATH,moveSpeed=moveSpeed)

        # 2. 指定敌机的初始随机速度 1 ~ 3
        # self.speed = random.randint(1, )

        # 3. 指定敌机的初始随机位置
        self.rect.bottom = 0

        max_x = SCREEN_RECT.width - self.rect.width
        self.rect.x = random.randint(0, max_x)

    def update(self):
        self.rect.y += self.moveSpeed
        # 判断是否飞出屏幕，如果是，需要从精灵组删除敌机
        if self.rect.y >= SCREEN_RECT.height:
            # print("飞出屏幕，需要从精灵组删除...")
            # kill方法可以将精灵从所有精灵组中移出，精灵就会被自动销毁
            self.kill()


if __name__ == '__main__':
    s = PlayerPlaneSprite()
    g = Group(s)
    print(PlayerPlaneSprite.__mro__)
